package com.novellotus.iov.carvice.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.TextView;

import com.ljd.retrofit.progress.ProgressHelper;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.rxjava.MyObserver;
import com.novellotus.iov.carvice.utils.HandlerUtils;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.tbruyelle.rxpermissions2.Permission;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * 关于我们
 */
public class AboutActivity extends BaseActivity implements HandlerUtils.OnReceiveMessageListener {

    @BindView(R.id.tv_tittle)
    TextView tv_tittle;
    @BindView(R.id.btn_update)
    TextView btn_update;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    String des = "", url = "";
    private HandlerUtils.HandlerHolder handlerHolder;

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_about);
    }


    @Override
    public void init() {
        handlerHolder = new HandlerUtils.HandlerHolder(this);
        if (getIntent().getExtras() != null && getIntent().getExtras().getString("url") != null) {
            des = getIntent().getExtras().getString("des");
            url = getIntent().getExtras().getString("url");
            btn_update.setVisibility(View.VISIBLE);
        } else {
            btn_update.setVisibility(View.GONE);
        }
        tv_tittle.setText("关于新荷");
    }


    @OnClick(R.id.img_back)
    void back() {
        finish();
    }

    @OnClick(R.id.btn_update)
    void upDate() {
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> e) throws Exception {
                e.onNext(1);
            }
        })
                .compose(RxSchedulers.lifecycle(this))
                .compose(rxPermissions.ensureEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)).subscribe(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) throws Exception {
                if (permission.granted) {
                    if (!ProgressHelper.DOWNLOADING) {

                        RetrofitFactory.getDownLoadInstance(AboutActivity.this, "版本更新", des).downloadFile(url)
                                .subscribeOn(Schedulers.io()).observeOn(Schedulers.io())
                                .subscribe(new MyObserver<ResponseBody>() {
                                    @Override
                                    public void onNext(ResponseBody responseBody) {
                                        super.onNext(responseBody);
                                        MyUtils.logInformation("下載成功！@！~！~！~！~");
                                        ProgressHelper.outPutApk(responseBody.byteStream(), AboutActivity.this);
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        super.onError(e);
                                        Message message = new Message();
                                        message.what = 0;
                                        message.obj = e.toString();
                                        handlerHolder.sendMessage(message);
                                    }
                                });
                    } else {
                        MyUtils.showToast(AboutActivity.this, "正在下载最新应用");
                    }

                } else {
                    MyUtils.showToast(AboutActivity.this, "读写手机存储权限被禁止，请在设置中允许相关权限");
                }
            }
        });

    }


    /**
     * 调用拨号界面
     */
    AlertDialog alertDialog;

    @OnClick(R.id.rlt_call_phone)
    void call() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        alertDialog = builder.create();
        builder.setMessage("新荷平台客服电话:" + getResources().getString(R.string.phone));
        builder.setPositiveButton("拨打", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Observable.create(new ObservableOnSubscribe<Object>() {
                    @Override
                    public void subscribe(ObservableEmitter<Object> e) throws Exception {
                        e.onNext("");
                    }
                }).compose(RxSchedulers.lifecycle(AboutActivity.this)).throttleFirst(1, TimeUnit.SECONDS)
                        .compose(rxPermissions.ensureEach(Manifest.permission.CALL_PHONE)).subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + getResources().getString(R.string.phone)));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                alertDialog.dismiss();
            }
        });

        builder.show();


    }

    @Override
    public void handlerMessage(Message msg) {
        MyUtils.showToast(AboutActivity.this, msg.obj.toString());
    }
}
